<?php

namespace app\common\model\imchat;

use app\common\model\User;
use think\Model;
use think\facade\Db;

class RoomUser extends Model
{
    // 表名
    protected $name = 'imchat_room_user';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = null;

    /**
     * 按分组获取所有的用户提供聊天室分配 后台分配
     * @param  [type] $ids [description]
     * @return [type]      [description]
     */
    public static function getAllUserToSelect($ids)
    {
        $user_ret = [];
        // 获取所有的前台用户 按类别
        $user_groups = Db::name('user_group')->field('id, name')->select();
        foreach ($user_groups as $v) {
            $user_ret[] =
                [
                    "id" => "group_{$v['id']}",
                    "parent" => "#",
                    "text" => $v['name'],
                    "state" => [
                        "selected" => false
                    ]];
            $users = Db::name('user')->field('id, username,nickname')->where('group_id', $v['id'])->select();
            foreach ($users as $value) {
                $user_ret[] =
                    [
                        "id" => $value['id'],
                        "parent" => "group_{$v['id']}",
                        "text" => $value['username'] . "@" . $value['nickname'],
                        "state" => [
                            "selected" => self::where('uid', $value['id'])->where('room_id', $ids)->find() ? true : false //是否在此聊天是内
                        ]];
            }
        }
        return $user_ret;
    }

    /**
     * 找出可以聊天的所有用户 默认全员可以聊天 添加type
     * @return array
     */
    public static function getChatUsersList($uid = 0)
    {

        $result=collect(
            (new Friends())->where([
                ['from_uid','=', $uid],
                ['to_uid','<>', 10]
            ])
                ->with('user')
                ->select()
        )->toArray();

        $last_msg = (new Message())->where(['to_uid' => 10, 'from_uid' => $uid])->order('id', 'desc')
            ->find();
        if(!$last_msg){
            $last_msg = (new Message())->where(['to_uid' => $uid, 'from_uid' => 10])->order('id', 'desc')
                ->find();
        }
        $last_msg_text = '';
        $v['type'] = $last_msg['type'] ?? 0;
        if ($last_msg) {
            switch ($last_msg['type']) {
                case 0:
                    $last_msg_text = $last_msg['content'];
                    break;
                case 1:
                    $last_msg_text = '房源信息';
                    break;
                case 2:
                    $last_msg_text = '找店信息';
                    break;
                case 3:
                    $last_msg_text = '【图片】';
                    break;
                case 4:
                    $last_msg_text = '【视频】';
                    break;
            }
        }
        $rsult=[[
            'id'=>10,
            'username'=>'rebort',
            'nickname'=>'平台通知',
            'avatar'=>'/static/images/avatar_rebot.png',
            'domain_avatar'=>request()->domain().'/static/images/avatar_rebot.png',
            'motto'=>'官方通知',
            'unread_count'=> Message::where(['to_uid' =>$uid, 'from_uid' => 10])->where('status', 0)->count('id'),
            'last_message'=>$last_msg_text?$last_msg_text:'欢迎你',
            'last_time'=>$last_msg?date('H:i', $last_msg['createtime']):''
        ]];
        foreach ($result as $k => $v) {
            if($v['to_uid']!=10){

                $last_msg = (new Message())
                    ->where(['to_uid' => $v['to_uid'], 'from_uid' => $uid])
                    ->whereOr(function ($query) use ($v,$uid) {
                        $query->where(['to_uid' =>  $uid, 'from_uid' =>$v['to_uid']]);
                    })
                    ->order('id', 'desc')
                    ->find();
//                if(!$last_msg){
//                    $last_msg = (new Message())->where(['to_uid' => $uid, 'from_uid' => $v['to_uid']])->order('id', 'desc')
//                        ->find();
//                }
                $last_msg_text = '';
                $v['type'] = $last_msg['type'] ?? 0;
                if ($last_msg) {
                    switch ($last_msg['type']) {
                        case 0:
                            $last_msg_text = $last_msg['content'];
                            break;
                        case 1:
                            $last_msg_text = '房源信息';
                            break;
                        case 2:
                            $last_msg_text = '找店信息';
                            break;
                        case 3:
                            $last_msg_text = '【图片】';
                            break;
                        case 4:
                            $last_msg_text = '【视频】';
                            break;
                    }
                }
                $return_arr=[
                    'id'=>$v['to_uid'],
                    'username'=>$v['user']?$v['user']['username']:'-',
                    'nickname'=>$v['user']?$v['user']['nickname']:'-',
                    'avatar'=>$v['user']?$v['user']['avatar']:'-',
                    'domain_avatar'=>$v['user']?request()->domain().$v['user']['avatar']:'-',
                    'motto'=>$v['user']?$v['user']['motto']:'',
                    'unread_count'=> Message::where(['to_uid' => $uid, 'from_uid' => $v['to_uid']])->where('status', 0)->count('id'),
                    'last_message'=>$last_msg_text,
                    'last_time'=>$last_msg?date('H:i', $last_msg['createtime']):''
                ];
                $rsult[]=$return_arr;
            }
        }
        return $rsult;
        return array_map(function ($v) use ($uid) {
            $last_msg = Message::where(['to_uid' => $v['id'], 'from_uid' => $uid])->order('id', 'desc')
                ->find();
            if(!$last_msg){
                $last_msg = Message::where(['to_uid' => $uid, 'from_uid' => $v['id']])->order('id', 'desc')
                    ->find();
            }
            $last_msg_text = '';
            $v['type'] = $last_msg['type'] ?? 0;
            if ($last_msg) {
                switch ($last_msg['type']) {
                    case 0:
                        $last_msg_text = $last_msg['content'];
                        break;
                    case 1:
                        $last_msg_text = '房源信息';
                        break;
                    case 2:
                        $last_msg_text = '找店信息';
                        break;
                    case 3:
                        $last_msg_text = '【图片】';
                        break;
                    case 4:
                        $last_msg_text = '【视频】';
                        break;
                }
            }
            $return_arr=[
                'id'=>$v['to_uid'],
                'username'=>$v['user']['username'],
                'nickname'=>$v['user']['nickname'],
                'avatar'=>$v['user']['avatar'],
                'domain_avatar'=>request()->domain().$v['user']['avatar'],
                'motto'=>$v['user']['motto'],
                'unread_count'=> Message::where(['to_uid' => $v['id'], 'from_uid' => $uid])->where('status', 0)->count('id'),
                'last_message'=>$last_msg_text,
            ];
            return $return_arr;
//            $v['unread_count'] = Message::where(['to_uid' => $v['id'], 'from_uid' => $uid])->where('status', 0)->count('id');
//
//            $v['last_message'] = $last_msg_text;
//            return $v;
        }, $result);


        $ret = collect((new User())
            ->field('id, username, nickname, avatar, motto')
            ->where('status', 'enable')
            ->select())->toArray();
        return array_map(function ($v) use ($uid) {
            $v['unread_count'] = Message::where(['to_uid' => $v['id'], 'from_uid' => $uid])->where('status', 0)->count('id');
            $last_msg = Message::where(['to_uid' => $v['id'], 'from_uid' => $uid])->order('createtime', 'desc')
                ->find();
            $last_msg_text = '';
            $v['type'] = $last_msg['type'] ?? 0;
            if ($last_msg) {
                switch ($last_msg['type']) {
                    case 0:
                        $last_msg_text = $last_msg['content'];
                        break;
                    case 1:
                        $last_msg_text = '房源信息';
                        break;
                    case 2:
                        $last_msg_text = '找店信息';
                        break;
                    case 3:
                        $last_msg_text = '【图片】';
                        break;
                    case 4:
                        $last_msg_text = '【视频】';
                        break;
                }
            }
            $v['last_message'] = $last_msg_text;
            return $v;
        }, $ret);


    }
    public static function getChatUsersList2($uid = 0)
    {



        $ret = collect((new User())
            ->field('id, username, nickname, avatar, motto')
            ->where('status', 'enable')
            ->select())->toArray();
        return array_map(function ($v) use ($uid) {
            $v['unread_count'] = Message::where(['to_uid' => $v['id'], 'from_uid' => $uid])->where('status', 0)->count('id');
            $last_msg = Message::where(['to_uid' => $v['id'], 'from_uid' => $uid])->order('createtime', 'desc')
                ->find();
            $last_msg_text = '';
            $v['type'] = $last_msg['type'] ?? 0;
            if ($last_msg) {
                switch ($last_msg['type']) {
                    case 0:
                        $last_msg_text = $last_msg['content'];
                        break;
                    case 1:
                        $last_msg_text = '房源信息';
                        break;
                    case 2:
                        $last_msg_text = '找店信息';
                        break;
                    case 3:
                        $last_msg_text = '【图片】';
                        break;
                    case 4:
                        $last_msg_text = '【视频】';
                        break;
                }
            }
            $v['last_message'] = $last_msg_text;
            return $v;
        }, $ret);


    }

    /**
     * 根据用户查询其已经加入的群组id 以数组展示
     * @param int $uid
     * @return array
     */
    public static function getRoomIdByUser($uid)
    {
        $g = collect(self::field('room_id')
            ->where('uid', $uid)
            ->select())->toArray();
        // 再取出特殊群组 比如所有群聊
        $s_group = collect(Room::field('id')
            ->where('status', "1")
            ->where('id', '<', 100)
            ->select())->toArray();
        return array_merge(array_column($s_group, 'id'), array_column($g, 'room_id'));
    }
}
